﻿Imports System.Text
Imports System.Net
Imports System.Xml

Namespace TwitterAPI
    Friend Class Connection
        Private twitterUri As New Uri("http://www.twitter.com")
        Private credentials As ICredentials
        Private cookies As New CookieContainer

        Friend Sub New(ByVal credentials As ICredentials)
            Me.credentials = credentials
            If Not ValidateCredentials(credentials.GetCredential(twitterUri, "").UserName, credentials.GetCredential(twitterUri, "").Password) Then
                Throw New InvalidOperationException("The supplied user name or password is incorrect")
            End If
        End Sub

        Public Function ValidateCredentials(ByVal username As String, ByVal password As String) As Boolean
            Dim request = CreateRequest("http://twitter.com/account/verify_credentials.xml")

            Try
                Using response = request.GetResponse()
                    Using reader = XmlReader.Create(response.GetResponseStream())
                        If reader.ReadToDescendant("user") And
                            reader.ReadToDescendant("screen_name") And
                            reader.ReadElementContentAsString() = username Then
                            Return True
                        End If
                    End Using
                End Using
            Catch ex As WebException
                Return False
            End Try

            Return False
        End Function

        Friend Function CreateRequest(ByVal uri As String) As WebRequest
            Dim request = WebRequest.Create(uri)
            Dim http = TryCast(request, HttpWebRequest)
            If http IsNot Nothing Then
                http.CookieContainer = cookies
            End If
            request.Credentials = credentials
            Return request
        End Function

        Friend Function CreateRequestWithUserName(ByVal uri As String) As WebRequest
            Return CreateRequest(String.Format(uri, credentials.GetCredential(New Uri("http://www.twitter.com"), "").UserName))
        End Function
    End Class
End Namespace
